#include"../include/lib_headers.h"

char* export_file(char *source_file_with_path, char *destination_file_path) {
	node *temp;
	int i;
	char str1[SIZE]="", ch, str[(BLOCKSIZE) + 1] = "";
			
	/* VFS not Mounted */	
	if (h == NULL || l1 == NULL) {
		sprintf(output_message,"%s %s","exportfile_FAILURE",ERR_VFS_EXPORTFILE_04);	
		return output_message;
	}

	/* Insufficient Arguments */
	if(strlen(source_file_with_path) == 0 || strlen(destination_file_path) == 0){
		sprintf(output_message,"%s %s","exportfile_FAILURE",ERR_VFS_EXPORTFILE_00);	
		return output_message;
	}

	/* Cannot export a directoy, only a file can be exported */	
	if(strcmp(source_file_with_path,"/")==0){
		sprintf(output_message,"%s %s","exportfile_FAILURE",ERR_VFS_EXPORTFILE_03);	
		return output_message;
	}

	/*Just made the string mutable */
	strcpy(str1,add_slash(source_file_with_path));
	
	/*Source file cannot be found*/
	//if (find_node(l1->next, str1) == NULL) {
	if (search(bstRoot, source_file_with_path) == NULL || source_file_with_path[0] != '/') {
		sprintf(output_message,"%s %s","exportfile_FAILURE",ERR_VFS_EXPORTFILE_01);	
		return output_message;
	} else
		temp = find_node(l1->next, str1);
		
	/* Cannot export a directoy, only a file can be exported */	
	if(strcmp(find_node(l1->next, str1)->fd_pointer->fileType, "dir") == 0){
		sprintf(output_message,"%s %s","exportfile_FAILURE",ERR_VFS_EXPORTFILE_03);	
		return output_message;
	}	
	
	/* Extensions should match */
	if(strcmp(file_extension(find_node(l1->next, source_file_with_path)->fd_pointer->fileName), 
			file_extension(destination_file_path)) != 0){	
		sprintf(output_message,"%s %s","exportfile_FAILURE",ERR_VFS_EXPORTFILE_02);	
		return output_message;
	}
	
	/* Output file cannot be created */
	FILE *f = fopen(destination_file_path, "wb");
	if (f == NULL) {
		sprintf(output_message,"%s %s","exportfile_FAILURE",ERR_VFS_EXPORTFILE_02);	
		return output_message;
	}

	FILE *fp = fopen(h->VFS_Label, "rb");
	if (fp == NULL) {
		sprintf(output_message,"%s %s","exportfile_FAILURE",ERR_VFS_EXPORTFILE_01);	
		return output_message;
	}

	fseek(fp,sizeof(hd),SEEK_SET);
	fseek(fp,sizeof(fd) * h->maxFds,SEEK_CUR);
	fseek(fp,sizeof(int) * h->maxFds,SEEK_CUR);
	for(i=0;i<temp->fd_pointer->blockno;i++)
		fseek(fp,(BLOCKSIZE), SEEK_CUR);
	i = 0;
	while(i != temp->fd_pointer->fileSize){
		ch = getc(fp);
		putc(ch, f);
		i++;
	}

	fclose(fp);
	fclose(f);
	sprintf(output_message,"%s","exportfile_SUCCESS");	
	return output_message;
}

